<template>
  <div class="map-component">
    <div v-if="type === 'map-china' || type === 'map-world'" ref="mapRef" class="echarts-map" />
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch, computed } from 'vue'
import * as echarts from 'echarts'

const props = defineProps({
  type: {
    type: String,
    required: true
  },
  props: {
    type: Object,
    default: () => ({})
  }
})

const mapRef = ref(null)
let chartInstance = null

const getMapName = () => {
  if (props.type === 'map-china') return 'china'
  if (props.type === 'map-world') return 'world'
  return ''
}

const renderMap = async () => {
  if (!mapRef.value) return
  if (!chartInstance) {
    chartInstance = echarts.init(mapRef.value)
  }
  // 动态加载地图JSON（这里只做简单演示，实际项目建议用异步加载）
  if (props.type === 'map-china') {
    // 简单内置中国地图（可换成异步加载）
    if (!echarts.getMap('china')) {
      const res = await fetch('https://geo.datav.aliyun.com/areas_v3/bound/geojson?code=100000_full')
      const geoJson = await res.json()
      echarts.registerMap('china', geoJson)
    }
  } else if (props.type === 'map-world') {
    if (!echarts.getMap('world')) {
      const res = await fetch('https://echarts.apache.org/examples/data/asset/geo/world.json')
      const geoJson = await res.json()
      echarts.registerMap('world', geoJson)
    }
  }
  const option = {
    tooltip: { trigger: 'item' },
    geo: {
      map: getMapName(),
      roam: props.props.roam,
      zoom: props.props.zoom,
      center: props.props.center,
      label: { show: props.props.showLabel, color: '#fff' },
      itemStyle: {
        areaColor: '#0d2a42',
        borderColor: '#409EFF',
        borderWidth: 1
      },
      emphasis: {
        itemStyle: {
          areaColor: '#67C23A',
          shadowColor: '#409EFF',
          shadowBlur: 10
        }
      }
    },
    series: [
      {
        type: 'map',
        map: getMapName(),
        geoIndex: 0,
        data: props.props.data || []
      }
    ]
  }
  chartInstance.setOption(option)
}

onMounted(() => {
  renderMap()
})

watch(() => props.props, () => {
  renderMap()
}, { deep: true })

onUnmounted(() => {
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
})
</script>

<style scoped>
.map-component {
  width: 100%;
  height: 100%;
  position: relative;
}
.echarts-map {
  width: 100%;
  height: 100%;
  min-height: 200px;
}
</style> 